package cn.schoolwow.util.module.crypto.cipher.rsa.flow;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.check.instance.CheckInstance;
import cn.schoolwow.util.module.crypto.cipher.rsa.domain.RSACipherOption;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class RSAEncryptFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        RSACipherOption rsaCipherOption = flowContext.checkInstanceData(RSACipherOption.class);

        CheckInstance.newCheck()
                .notNullCheck(rsaCipherOption.publicKey, "RSA算法公钥不能为空");
        if(null==rsaCipherOption.data||rsaCipherOption.data.isEmpty()){
            flowContext.broken("明文内容为空");
        }

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, rsaCipherOption.publicKey);
        byte[] encrypted = cipher.doFinal(rsaCipherOption.data.getBytes(StandardCharsets.UTF_8));
        String base64String = Base64.getEncoder().encodeToString(encrypted);
        flowContext.putReturnData("string", base64String);
    }

    @Override
    public String name() {
        return "RSA算法加密";
    }

}
